package dao

import (
	"goods-srv/internal/model"
	"goods-srv/libs"
)

func CreateUser(user model.User) (id uint64, err error) {
	db := libs.GetDB()
	user.Id = libs.GetId()
	user.Password = libs.GetSha256(user.Password)
	if user.Avatar == "" {
		user.Avatar = "https://img.paulzzh.tech/touhou/random"
	}
	if user.State == "" {
		user.State = "enable"
	}
	result := db.Create(&user)
	if result.Error != nil {
		return 0, result.Error
	}
	return user.Id, nil
}

func DeleteUser(id uint64) (err error) {
	db := libs.GetDB()
	result := db.Delete(&model.User{}, id)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

func UpdateUser(user model.User) (err error) {
	db := libs.GetDB()
	result := db.Model(&user).Updates(user)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

func SelectUserById(id uint64) (user model.User, err error) {
	db := libs.GetDB()
	result := db.First(&user, id)
	if result.Error != nil {
		return user, result.Error
	}
	return user, nil
}

func SelectUserByAccount(account string) (user model.User, err error) {
	db := libs.GetDB()
	result := db.Where(&model.User{Account: account}).First(&user)
	if result.Error != nil {
		return user, result.Error
	}
	return user, nil
}

func SelectUserByMobile(mobile string) (user model.User, err error) {
	db := libs.GetDB()
	result := db.Where(&model.User{Mobile: mobile}).First(&user)
	if result.Error != nil {
		return user, result.Error
	}
	return user, nil
}

func SelectUserList() (list []model.User, err error) {
	db := libs.GetDB()
	result := db.Find(&list)
	if result.Error != nil {
		return nil, result.Error
	}
	return list, nil
}

func SelectUserPageList(pageQuery *PageQuery) (list []model.User, err error) {
	pageQuery.Computed()
	var query model.User
	if pageQuery.Query != nil {
		query = pageQuery.Query.(model.User)
	}
	db := libs.GetDB()
	// 分页查询时，查询总条数要指定 Model, Count 要在 Where 之后
	result := db.Model(model.User{}).Where("name like ? and account like ? and mobile like ? and state like ?",
		"%"+query.Name+"%", "%"+query.Account+"%", "%"+query.Mobile+"%", "%"+query.State+"%").Count(&pageQuery.Page.Total).Order(pageQuery.Page.SortField + " " + pageQuery.Page.Sort).Offset(int(pageQuery.Page.Offset)).Limit(int(pageQuery.Page.PageSize)).Find(&list)
	if result.Error != nil {
		return list, result.Error
	}
	return list, nil
}
